﻿using Infrastructure.Managers;
using RhotCMS.Filters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Security;
using Utils;
using WebMatrix.WebData;

namespace RhotCMS.Models
{    
    public class MembershipRepository : UserManager
    {
        public override void RegisterUser(string userName, string password, string email, string lang, bool isRequireConfirmationToken)
        {
            if (!CheckUserEmailUnique(email))
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateEmail);
            }

            var token = WebSecurity.CreateUserAndAccount(userName, password, new { Email = email }, isRequireConfirmationToken);

            var confirmationUrl = String.Format("{0}{1}/Account/Confirm?accountConfirmationToken={0}", URLUtils.GetAbsVirtualAppPath(), CultureInfo.GetCultureInfo(lang).TwoLetterISOLanguageName, token);

            SendConfirmationToken(email, "Registration confirmation", String.Format("To confirm your registration click <a href=\"{0}\">here</a> ({0})", confirmationUrl));
        }

        public override string[] GetAllRoles()
        {
            var roles = Roles.GetAllRoles();
            return roles;
        }

        public override bool IsUserInRole(string userLogin, string roleName)
        {
            if (!CheckUserExist(userLogin))
                return false;

            return Roles.IsUserInRole(userLogin, roleName);
        }

        public override void AddUserToRole(string userLogin, string roleName)
        {
            Roles.AddUserToRole(userLogin, roleName);
        }

        public override void RemoveUserFromRole(string userLogin, string roleName)
        {
            Roles.RemoveUserFromRole(userLogin, roleName);
        }

        public override void DeleteUser(string userName)
        {
            Membership.DeleteUser(userName);
        }
    }
}